#pragma once // 防止头文件被重复包含
#include "t_queue.hpp"
#include "task.hpp"
#include <pthread.h>

#define T_MAX 100 // 线程池中的数量

class thread
{
public:
    static thread *get_thread()
    {
        if (thread_ptr == nullptr)
        {
            static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
            pthread_mutex_lock(&mutex); // 加锁
            if (thread_ptr == nullptr)
            {
                thread_ptr = new thread();
                thread_ptr->init();
            }
            pthread_mutex_unlock(&mutex); // 解锁
        }
        return thread_ptr;
    }

private:
    annular<task> _q; // 保证线程安全的任务容器
    int _n_max;       // 线程的数量
    static thread *thread_ptr;

    thread()
        : _n_max(T_MAX)
    {
    }

    thread(const thread &);

    static void *task_f(void *data)
    {
        thread *d = (thread *)data;
        task t;
        d->pop(t);
        t.e_task();
    }

    void init()
    {
        pthread_t pid;
        for (int i = 0; i < T_MAX; i++)
        {
            if (pthread_create(&pid, nullptr, task_f, (void *)this) != 0)
            {
                LOG(WARNING, "线程创建失败");
            }
        }
    }

    void pop(task &t)
    {
        _q.pop(t);
    }

    public:

    void push(task &t)
    {
        _q.push(t);
    }


};

thread *thread::thread_ptr = nullptr;